package com.liulimi.fastapi.utils.json;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * @author chenhao
 * @date 2021/01/11
 */
public class JsonUtil {
    private static ObjectMapper objectMapper;
    private static Logger logger;

    static {
        objectMapper = new ObjectMapper();
        logger = LoggerFactory.getLogger(JsonUtil.class);
    }

    public static String toJsonString(Object object){

        try {
            if (object == null){
                return "";
            }

            if (object instanceof Number){
                return object.toString();
            }
            return objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            logger.warn("Parse Object to String error", e);
            return "";
        }
    }


    public static <T> T toJavaObject(String jsonString,Class<T> clazz){
        if (StringUtils.isBlank(jsonString)){
            return null;
        }
        try {
            return objectMapper.readValue(jsonString,clazz);
        } catch (JsonProcessingException e) {
            logger.warn("Parse Object to String error : {}", e.getMessage());
            return null;
        }
    }


    public static <T> T toJavaObject(String str, TypeReference<T> typeReference) {
        if (StringUtils.isEmpty(str) || typeReference == null) {
            return null;
        }
        try {
            return (T) (typeReference.getType().equals(String.class) ? str : objectMapper.readValue(str, typeReference));
        } catch (IOException e) {
            logger.warn("Parse String to Object error", e);
            return null;
        }
    }

    public static <T> T toJavaObject(String str, Class<?> collectionClazz, Class<?>... elementClazzes) {
        JavaType javaType = objectMapper.getTypeFactory().constructParametricType(collectionClazz, elementClazzes);
        try {
            return objectMapper.readValue(str, javaType);
        } catch (IOException e) {
            logger.warn("Parse String to Object error : {}" + e.getMessage());
            return null;
        }
    }
}
